﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Facilities.AutomaticTransactionManagement;
using Castle.Facilities.NHibernateIntegration;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using log4net.Config;
using MvcContrib.Castle;
using NHATMSample.Controllers;
using NHATMSample.Service;
using NHibernate.Tool.hbm2ddl;

namespace NHATMSample {
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication, IContainerAccessor {
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Home", action = "Index", id = ""} // Parameter defaults
                );
        }

        protected void Application_Start() {
            BasicConfigurator.Configure();
            RegisterRoutes(RouteTable.Routes);
            SetupWindsor();
        }

        private static IWindsorContainer container;

        private void SetupWindsor() {
            container = new WindsorContainer(new XmlInterpreter());
            var configBuilder = new NHConfigBuilder(Server.MapPath("/"));
            container.AddFacility("nhibernate", new NHibernateFacility(configBuilder));
            container.AddFacility<TransactionFacility>();
            container.AddComponent<TransactionalService>();
            container.AddComponent<HomeController>("home");
            new SchemaExport(configBuilder.GetConfiguration(null)).Execute(false, true, false);
            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
        }

        public IWindsorContainer Container {
            get { return container; }
        }
    }
}